//
//  XMChatBar.m
//  XMChatBarExample
//
//  Created by shscce on 15/8/17.
//  Copyright (c) 2015年 xmfraker. All rights reserved.
//

#import "IMMessageBar.h"
#import <Masonry.h>
#import "UIView+Add.h"
#import "AppConfig.h"

static NSString *tvNText = @"从这里开始与世界沟通";

@interface IMMessageBar () <UITextViewDelegate>

@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UIButton *sendBtn;
@property (nonatomic,  copy ) NSString *inputText;
@end

@implementation IMMessageBar

- (instancetype)init {
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        [self setup];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

#pragma mark - api

- (void)sendMessage {
    
    [self endEditing:YES];
    if (self.inputText.length == 0) {
        [self textViewNormal];
        return;
    }
    self.inputText = self.textView.text;
    [self textViewNormal];
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBar:sendMessage:)]) {
        [self.delegate chatBar:self sendMessage:self.inputText];
        self.inputText = @"";
    }
}

///发送语音
- (void)sendVoiceMessage:(NSString *)voiceFileName seconds:(NSTimeInterval)seconds{
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBar:sendVoice:seconds:)]) {
        [self.delegate chatBar:self sendVoice:voiceFileName seconds:seconds];
    }
}

/// 发送图片
- (void)sendImageMessage:(UIImage *)image {
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBar:sendPictures:)]) {
        [self.delegate chatBar:self sendPictures:@[image]];
    }
}


#pragma mark - NSNotification
- (void)keyboardFrameWillChange:(NSNotification *)notification {
    
    [self.superview bringSubviewToFront:self];
    
    CGFloat durtion = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect frame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    if (frame.origin.y == [UIScreen mainScreen].bounds.size.height) {
        
        //        self.backgroundColor = [UIColor clearColor];
        [UIView animateWithDuration:durtion animations:^{
            self.transform =  CGAffineTransformIdentity;
        }];
    } else {
        
        //        self.backgroundColor = [UIColor blackColor];
        [UIView animateWithDuration:durtion animations:^{
            self.transform = CGAffineTransformMakeTranslation(0, -frame.size.height);
        }];
    }
}


#pragma mark - UITextViewDelegate

- (void)textViewDidBeginEditing:(UITextView *)textView {
    textView.text = @"";
}
- (void)textViewDidEndEditing:(UITextView *)textView {
    self.inputText = textView.text;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if ([text isEqualToString:@"\n"]) {
        [self sendMessage];
        return NO;
    } /*else if (text.length == 0) {
       return YES;
       //判断删除的文字是否符合表情文字规则
       NSString *deleteText = [textView.text substringWithRange:range];
       if ([deleteText isEqualToString:@"]"]) {
       NSUInteger location = range.location;
       NSUInteger length = range.length;
       NSString *subText;
       while (YES) {
       if (location == 0) {
       return YES;
       }
       location -- ;
       length ++ ;
       subText = [textView.text substringWithRange:NSMakeRange(location, length)];
       if (([subText hasPrefix:@"["] && [subText hasSuffix:@"]"])) {
       break;
       }
       }
       textView.text = [textView.text stringByReplacingCharactersInRange:NSMakeRange(location, length) withString:@""];
       [textView setSelectedRange:NSMakeRange(location, 0)];
       [self textViewDidChange:self.textView];
       return NO;
       }
       }*/
    return YES;
}


//- (void)textViewDidChange:(UITextView *)textView {
//    CGRect textViewFrame = self.textView.frame;
//
//    CGSize textSize = [self.textView sizeThatFits:CGSizeMake(CGRectGetWidth(textViewFrame), 1000.0f)];
//
//    CGFloat offset = 10;
//    textView.scrollEnabled = (textSize.height + 0.1 > kMaxHeight-offset);
//    textViewFrame.size.height = MAX(34, MIN(kMaxHeight, textSize.height));
//
//    CGRect addBarFrame = self.frame;
//    addBarFrame.size.height = textViewFrame.size.height + offset;
//    if (textView.scrollEnabled) {
//        [textView scrollRangeToVisible:NSMakeRange(textView.text.length - 2, 1)];
//    }
//}


- (void)setup {
    
    [self addSubview:self.sendBtn];
    [self addSubview:self.textView];
    
    [self.sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self);
        make.bottom.equalTo(self);
        make.width.equalTo(@72);
        make.height.equalTo(@31.5);
    }];
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self);
        make.right.equalTo(self.sendBtn.mas_left).offset(-1);
        make.top.equalTo(self);
        make.bottom.equalTo(self.sendBtn.mas_bottom);
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardFrameWillChange:)
                                                 name:UIKeyboardWillChangeFrameNotification
                                               object:nil];
    [self textViewNormal];
    
}

- (void)textViewNormal {
    _textView.text = tvNText;
    _textView.textColor = YiGray;
}


#pragma mark -

- (UIButton *)sendBtn {
    
    if (!_sendBtn) {
        _sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sendBtn setImage:[UIImage imageNamed:@"send_button_0"] forState:UIControlStateNormal];
        [_sendBtn setImage:[UIImage imageNamed:@"send_button_0h"] forState:UIControlStateHighlighted];
        [_sendBtn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _sendBtn;
}

//从这里开始与世界沟通
- (UITextView *)textView {
    if (!_textView) {
        
        _textView = [[UITextView alloc] init];
        _textView.font = [UIFont systemFontOfSize:13.0f];
        _textView.delegate = self;
        _textView.layer.borderColor = RGBA(50, 105, 123, 1).CGColor;
        _textView.backgroundColor = RGBA(8, 12, 21, 1);
        _textView.layer.borderWidth = 1.5f;
    }
    return _textView;
}

@end
